<template>
  <el-dialog v-model="visible" title="图书详情" class="book-detail-dialog" @close="closeDialog">
    <div class="book-detail-container">
      <div class="book-image">
        <img :src="$urlImage+book.imgSrc" alt="图书封面" class="book-cover">
      </div>
      <div class="book-info">
        <div class="book-title">{{ book.name }}</div>
        <div class="book-author">作者：{{ book.author }}</div>
        <div class="book-publisher">出版社：{{ book.publisher }}</div>
        <div class="book-price">价格：￥{{ book.price }}</div>
        <div class="book-intro">
          <p>简介：{{ book.detail }}</p>
        </div>
        <div class="action-buttons">
          <el-button type="primary" @click="addToCart">加入购物车</el-button>
          <el-button type="success" @click="buy">购买</el-button>
          <el-button type="text" @click="toggleFavorite" :class="{ 'is-favorite': isFavorite }">
            <el-icon :style="{ color: isFavorite ? '#ff7d00' : '#c0c4cc' }">
              <StarFilled  />
            </el-icon>
            <span>{{ isFavorite ? '已收藏' : '待收藏' }}</span>
          </el-button>
          <el-button type="info" @click="closeDialog">关闭</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import {computed, onMounted, ref, watch} from 'vue';
import axios from "axios";
import { userStore } from '@/store/index.js'
import {ElMessage} from "element-plus";
const userItemStore = userStore();
// 在 script 中引入所需图标
import {StarFilled } from '@element-plus/icons-vue'
// 在 setup 中注册图标
const icons = {
  StarFilled
}

//收藏
const isFavorite = ref(false); // 当前书籍收藏状态

// 切换收藏状态
const toggleFavorite = () => {

  isFavorite.value = !isFavorite.value;
  if (isFavorite.value==true) {
    //保存 收藏
    saveFavoriteToServer(book.value.id);

  } else {
    removeFavoriteFromServer(book.value.id);

  }
  // 触发收藏状态变更事件
  emits('favoriteChanged', {
    bookId: book.value.id,
    isFavorite: isFavorite.value
  });

};

// 收藏书籍到服务器
const saveFavoriteToServer = (bookId) => {
  axios.post(`/bookCollection/addCollection/${userItemStore.user.id}/${bookId}`)
      .then(resp => {
        userItemStore.addFavorite(bookId);
        ElMessage.success(resp.data);
      })
};


// 从服务器取消收藏
const removeFavoriteFromServer = (bookId) => {

  axios.delete(`/bookCollection/deleteCollection/${userItemStore.user.id}/${bookId}`)
      .then(resp => {
        ElMessage.success(resp.data);
        //存储图书id
        userItemStore.removeFavorite(bookId);
      })
};

// 检查书籍是否已收藏
const checkBookFavoriteStatus = (bookId) => {
  // axios.post(`/bookCollection/checkIsStorage/${userItemStore.user.id}/${bookId}`)
  //     .then(resp => {
  //       isFavorite.value = resp.data; //查询
  //     })
  if (userItemStore.favoriteMap[bookId]) {
    isFavorite.value = true;
  } else {
    isFavorite.value = false;
  }
};

// 声明props
const props = defineProps({
  detailDialog: {
    type: Boolean,
    default: false
  },
  bookId: {
    type: Number,
    required: true
  }
});



// 控制对话框显示状态
const visible = ref(false);

// 加入购物车方法
const addToCart = () => {
  if(userItemStore.user.id!==undefined && userItemStore.user.id!==null){
    axios.post(`/cart/addToCart/${userItemStore.user.id}`, book.value).then((resp) => {
      ElMessage.success(resp.data);
    })
  }else {
    ElMessage.error("请先登陆！");
  }


};

// 购买方法
const buy = () => {
  console.log('已购买');
};

// 关闭对话框方法
const closeDialog = () => {
  visible.value = false;
  emits("visible",visible.value);
};
const emits = defineEmits("");


watch(()=>props.detailDialog,(newValue)=>{
  visible.value = props.detailDialog;
});
// watch(() => props.detailDialog, (newValue) => {
//   visible.value = newValue;
// });


// 模拟图书数据
const book = ref({});

watch(()=>props.bookId,(newValue)=>{
  if (!newValue) return;
  axios.post(`/book/getBookById/${props.bookId}`).then((resp)=>{
    book.value = resp.data;
    checkBookFavoriteStatus(newValue); // 加载完图书后检查收藏状态
  })
})

// 监听userStore的favoriteMap变化，同步更新组件状态
watch(
    () => userItemStore.favoriteMap,
    (newFavoriteMap) => {
      if (props.bookId) {
        checkBookFavoriteStatus(props.bookId);
      }
    },
    { deep: true }
)

// 组件挂载时检查登录状态和收藏状态
onMounted(() => {
  if (props.bookId && userItemStore.loggedIn) {
    checkBookFavoriteStatus(props.bookId);
  }
});


</script>

<style scoped>
/* 收藏按钮动画效果 */
.is-favorite .el-icon-heart {
  animation: heartBeat 0.3s ease-in-out;
}

@keyframes heartBeat {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}





.book-detail-dialog {
  width: 800px;
  max-width: 80%;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
}

.book-detail-container {
  display: flex;
  align-items: flex-start;
}

.book-image {
  width: 200px;
  margin-right: 20px;
}

.book-cover {
  width: 100%;
  height: auto;
}

.book-info {
  flex: 1;
}

.book-title {
  font-size: 24px;
  margin-bottom: 10px;
  color: #333;
}

.book-author,
.book-publisher,
.book-price {
  font-size: 16px;
  margin-bottom: 5px;
  color: #666;
}

.book-intro p {
  margin: 10px 0;
  color: #333;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>